<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1, maximum-scale=1">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>产品库</title>
    <link rel="stylesheet" href="/business/css/common.min.css">
    <link rel="stylesheet" href="/business/mescroll/mescroll.min.css">
    <link rel="stylesheet" href="/business/css/layer.css">
    <script src="/business/js/jquery-1.11.1.min.js"></script>
    <script src="/business/js/layer.mobile.js"></script>
</head>

<body class="product_page">

    <div class="header">
        <a href="{{url('product/search')}}"></a>
        <ul class="clearfix">
            @if($categories->count())
                @foreach($categories as $k=>$category)
                    <li onclick="loanRequire(this)" i="{{$k}}" class="{{$k==0?'on':''}}">{{$category->name}}</li>
                @endforeach
            @endif
        </ul>
    </div>

    @if($categories->count())
        @foreach($categories as $k=>$category)
            <div class="mescroll content {{$k==0?'':'none'}}" id="mescroll{{$k}}">
                @if($category->hots->count())
                    <div class="wrapper wrapper{{1+$k}}">
                        <div class="scroller scroller{{1+$k}}">
                            <ul class="clearfix">
                                @foreach($category->hots as $k2=>$hot)
                                    <li>
                                        <a href="{{url('product/show',['id'=>$hot->id])}}"
                                           class="{{$k2==0?'on':''}}">
                                            <p class="title">{{$hot->basic_info['agent_name'].'-'.$hot->name}}</p>
                                            <p class="num">{{$hot->basic_info['loan_start'].'-'.$hot->basic_info['loan_end']}}</p>
                                            <p class="text">贷款额度（万元）</p>
                                            <div class="clearfix fo">
                                                <p>最低月利率：{{$hot->basic_info['rate_start']}}%</p>
                                                <p>期限：{{$hot->basic_info['repay_start'].'-'.$hot->basic_info['repay_end']}}月</p>
                                            </div>
                                        </a>
                                    </li>
                                @endforeach
                            </ul>
                        </div>
                    </div>
                @endif

                {{--产品列表--}}
                @if($category->products->count())
                    <div class="product_list">
                    <p class="p"><i></i><span>产品</span></p>
                    <ul class="product_list_msg" id="dataList{{$k}}">
                        {{--@foreach($category->products as $k3=>$product)
                            <li class="shadow">
                                <a href="{{url('product/show',['id'=>$product->id])}}">
                                    <div class="top">
                                        <div class="clearfix item_t">
                                            <div>
                                                @if(isset($product->basic_info['agent_logo']))
                                                    <img src="{{env('IMG_URL').$product->basic_info['agent_logo']}}" alt="">
                                                @else
                                                    <img src="/business/images/logo-1.png" alt="">
                                                @endif
                                            </div>
                                            <div>
                                                <p class="title">{{$product->name}}</p>
                                            </div>
                                            <div>
                                                <span>{{$product->apply_num}}</span>人申请
                                            </div>
                                            @if($product->tag_ids)
                                                    <p class="clearfix">
                                                        @foreach($product->tag_ids as $tag)
                                                            <span>{{$tag['name']}}</span>
                                                        @endforeach
                                                    </p>
                                                @endif
                                        </div>
                                        <div class="clearfix loanMsg">
                                            <div>
                                                <p>{{$product->basic_info['rate_start']}}%</p>
                                                <p>最低月利率</p>
                                            </div>
                                            <div>
                                                <p>{{$product->basic_info['loan_start'].'-'.$product->basic_info['loan_end']}}</p>
                                                <p>贷款额度(万元)</p>
                                            </div>
                                            <div>
                                                <p>{{$product->basic_info['repay_start'].'-'.$product->basic_info['repay_end']}}</p>
                                                <p>期限(月)</p>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="bot clearfix">
                                        --}}{{--<i class="pass"></i>--}}{{--
                                        <p>平均下款时间 : {{$product->basic_info['progress_start']}}天</p>
                                        <i class="corner"></i>
                                    </div>
                                </a>
                            </li>
                        @endforeach--}}
                    </ul>
                </div>
                @endif
            </div>
        @endforeach
    @endif


@include('Layouts.footer')


<script src="/business/js/base.js"></script>
<script src="/business/js/common.js"></script>
<script src="/business/mescroll/mescroll.min.js"></script>

<script type="text/javascript">


$.fn.scrollEnd = function(callback, timeout) {            
    $(this).scroll(function(){  
    var $this = $(this);  
    if ($this.data('scrollTimeout')) {  
        clearTimeout($this.data('scrollTimeout'));  
    }  
    $this.data('scrollTimeout', setTimeout(callback,timeout));  
    });  
};



    function initSwiper(key) {
        var k=1+parseInt(key);
        var w = $('.scroller'+k+' li').width();
        var len = $('.scroller'+k+' li').length
        $('.scroller'+k).width(len * w + w / 66 * 4)
        var i
        if (len === 3) {
            $('.scroller'+k).css('margin-left', -w)
            i = 1
        } else {
            $('.scroller'+k).css('margin-left', 0)
            i = 0
        }

//        console.log(len, i, $('.scroller'+k).css('margin-left'))
        var touch = new Touch($('.scroller'+k),80).init();
        //向左滑动触发事件
        touch.swipeLeft = function (dom) {
//            console.log('向左')
            if(i < len-1){
                i++
                $('.scroller'+k).animate({
                    marginLeft: -i*w
                },200)
//                console.log(len, i, $('.scroller'+k).css('margin-left'))
            }
        };
        //向右滑动事件
        touch.swipeRight = function (dom) {
//            console.log('向右')
            if(i > 0){
                i--
                $('.scroller'+k).animate({
                    marginLeft: -i*w
                },200)
//                console.log(len, i, $('.scroller'+k).css('margin-left'))
            }
        }
    }

    @if($categories->count())
        @foreach($categories as $k=>$category)
            initSwiper(Number('{{$k}}'));
            localStorage.setItem('totalPage_{{$k}}',Number("{{$category->products->lastPage()}}"));
            localStorage.setItem('url_{{$k}}',"{!! $category->products->url(1) !!}");
        @endforeach
    @endif

function Touch(dom,range) {  
    this.init = function () {  
        var that = this;  
        for(var i = 0; i<dom.length; i++){  
            (function (dom) {  
                function touchstart(event) {  
                    var e = event || window.event;  
                    if(e.targetTouches.length === 1){  
                        var startX = e.targetTouches[0].clientX,  
                            startY = e.targetTouches[0].clientY;  
                        function touchmove(e) {  
                            var moveEndX = e.targetTouches[0].clientX,  
                                moveEndY = e.targetTouches[0].clientY;  
                            if((that.getAngle(startX,startY,moveEndX,moveEndY) >= 135 || that.getAngle(startX,startY,moveEndX,moveEndY) <= -135) && that.getRange(startX,startY,moveEndX,moveEndY) >= range){  
                                that.swipeLeft(dom);  
                                dom.removeEventListener("touchmove",touchmove);  
                            }else if((that.getAngle(startX,startY,moveEndX,moveEndY) >= -45 && that.getAngle(startX,startY,moveEndX,moveEndY) <= 45)&& that.getRange(startX,startY,moveEndX,moveEndY) >= range){  
                                that.swipeRight(dom);  
                                dom.removeEventListener("touchmove",touchmove);  
                            }  
                        }  
                        function touchend() {  
                            dom.removeEventListener("touchend",touchend);  
                            dom.removeEventListener("touchmove",touchmove);  
                        }  
                        dom.addEventListener("touchmove",touchmove);  
                        dom.addEventListener("touchend",touchend);  
                    }  
                }  
                dom.addEventListener("touchstart",touchstart);  
            })(dom[i]);  
        }  
        return this;  
    };//计算滑动的角度  
    this.getAngle = function (px1, py1, px2, py2) {  
        //两点的x、y值  
        x = px2-px1;  
        y = py2-py1;  
        hypotenuse = Math.sqrt(Math.pow(x, 2)+Math.pow(y, 2));  
        //斜边长度  
        cos = x/hypotenuse;  
        radian = Math.acos(cos);  
        //求出弧度  
        angle = 180/(Math.PI/radian);  
        //用弧度算出角度  
        if (y<0) {  
            angle = -angle;  
        } else if ((y == 0) && (x<0)) {  
            angle = 180;  
        }  
        return angle;  
    };  
    //计算两点之间的距离  
    this.getRange = function (px1,py1,px2,py2) {  
        return Math.sqrt(Math.pow(Math.abs(px1 - px2), 2) + Math.pow(Math.abs(py1 - py2), 2));  
    };  
    this.swipeLeft = function (dom) {};  
    this.swipeRight = function (dom) {}  
}




    /*加载更多*/

    var tabNum=Number("{{$categories->count()}}");
    var curNavIndex=0;//
    var mescrollArr=new Array(tabNum);//4个菜单所对应的4个mescroll对象
    //初始化首页
    mescrollArr[0]=initMescroll("mescroll0", "dataList0");

    /*初始化菜单*/
    $(".header li").click(function(){
        var i=Number($(this).attr("i"));
        if(curNavIndex!=i) {
            //隐藏当前列表和回到顶部按钮
            $("#mescroll"+curNavIndex).hide();
            mescrollArr[curNavIndex].hideTopBtn();
            //显示对应的列表
            $("#mescroll"+i).show();

            //取出菜单所对应的mescroll对象,如果未初始化则初始化
            if(mescrollArr[i]==null){
                mescrollArr[i]=initMescroll("mescroll"+i, "dataList"+i);
                if(localStorage.getItem('url_'+i)==='null' || localStorage.getItem('url_'+i)===null){
//                    $('.mescroll-upwarp').hide();
                    return false;
                }
            }else{
                //检查是否需要显示回到到顶按钮
                var curMescroll=mescrollArr[i];
                var curScrollTop=curMescroll.getScrollTop();
                if(curScrollTop>=curMescroll.optUp.toTop.offset){
                    curMescroll.showTopBtn();
                }else{
                    curMescroll.hideTopBtn();
                }
            }
            //更新标记
            curNavIndex=i;
        }
    });



    /*创建MeScroll对象*/
    function initMescroll(mescrollId,clearEmptyId){
        //创建MeScroll对象,内部已默认开启下拉刷新,自动执行up.callback,刷新列表数据;
        var mescroll = new MeScroll(mescrollId, {
            //下拉刷新
            down: {
                use:true,
                auto: false, //是否在初始化完毕之后自动执行下拉回调callback; 默认true
//                callback: downCallback, //下拉刷新的回调
                callback: function () {
                    setTimeout(function () {
                        mescroll.endSuccess();
                    },2000);
                },
                htmlContent:'<div style="text-align: center" "><img style="width: 100px;margin-bottom: -6%;display: inline-block" src="/business/mescroll/img/loading.gif"><p>&nbsp;&nbsp;加载中...</p></div>'
            },
            //上拉加载的配置项
            up: {
                use:true,
                auto:true,
                callback: getListData, //上拉回调,此处可简写; 相当于 callback: function (page) { getListData(page); }
                isBounce: false, //此处禁止ios回弹,解析(务必认真阅读,特别是最后一点): http://www.mescroll.com/qa.html#q10
                noMoreSize: 5, //如果列表已无数据,可设置列表的总数量要大于半页才显示无更多数据;避免列表数据过少(比如只有一条数据),显示无更多数据会不好看; 默认5
//                empty: {
//                    icon: "../res/img/mescroll-empty.png", //图标,默认null
//                    tip: "暂无相关数据~", //提示
//                    btntext: "去逛逛 >", //按钮,默认""
//                    btnClick: function(){//点击按钮的回调,默认null
//                        alert("点击了按钮,具体逻辑自行实现");
//                    }
//                },
                clearEmptyId: clearEmptyId, //相当于同时设置了clearId和empty.warpId; 简化写法;默认null
                toTop:{ //配置回到顶部按钮
                    src:'/business/mescroll/img/mescroll-totop.png'
                },
                htmlNodata:'<p class="upwarp-nodata"> -- 没有更多数据了 -- </p>',
                empty:{
                    warpId : null ,
                    icon : null ,
                    tip : "暂无相关数据~" ,
                    btntext : "" ,
                    btnClick : null,
                    supportTap : false
                },
//                htmlLoading:'<p class="upwarp-progress mescroll-rotate"></p><p class="upwarp-tip">加载中..</p>',
                htmlLoading:'<div style="text-align: center" "><img style="width: 100px;margin-bottom: -6%;display: inline-block" src="/business/mescroll/img/loading.gif"><p>&nbsp;&nbsp;加载中...</p></div>'
            }
        });
        mescroll.setPageSize(Number("{{$pageSize}}"));
        return mescroll;
    }

//    function downCallback() {
//        mescroll.endSuccess();
//    }

    /*联网加载列表数据  page = {num:1, size:10}; num:当前页 从1开始, size:每页数据条数 */
    function getListData(page){
        //联网加载数据
        var dataIndex=curNavIndex; //记录当前联网的nav下标,防止快速切换时,联网回来curNavIndex已经改变的情况;
        getListDataFromNet(dataIndex, page.num, page.size, function(pageData){
            //联网成功的回调,隐藏下拉刷新和上拉加载的状态;
            //mescroll会根据传的参数,自动判断列表如果无任何数据,则提示空;列表无下一页数据,则提示无更多数据;
//            console.log("dataIndex="+dataIndex+", curNavIndex="+curNavIndex+", page.num="+page.num+", page.size="+page.size+", pageData.length="+pageData.length);

            //方法一(推荐): 后台接口有返回列表的总页数 totalPage
            var totalPage=Number(localStorage.getItem('totalPage_'+dataIndex));
            mescrollArr[dataIndex].endByPage(pageData.length, totalPage); //必传参数(当前页的数据个数, 总页数)

            //方法四 (不推荐),会存在一个小问题:比如列表共有20条数据,每页加载10条,共2页.如果只根据当前页的数据个数判断,则需翻到第三页才会知道无更多数据,如果传了hasNext,则翻到第二页即可显示无更多数据.
//            mescrollArr[dataIndex].endSuccess(pageData.length);

            //设置列表数据
            setListData(pageData,dataIndex);
        }, function(){
            //联网失败的回调,隐藏下拉刷新和上拉加载的状态;
            mescrollArr[dataIndex].endErr();
        });
    }

    /*设置列表数据
			 * pageData 当前页的数据
			 * dataIndex 数据属于哪个nav */
    function setListData(pageData,dataIndex){
        var html='';
        $(pageData).each(function (key,obj) {
            var tagHtml='';
            if(obj.tag_ids){
                if(obj.tag_ids.length>0){
                    $(obj.tag_ids).each(function (key2,tag) {
                        if(key2>1){
                            return false;
                        }
                        tagHtml +='<span>'+tag.name+'</span>';

                    });
                }
            }
            var agent_logo='/business/images/logo-1.png';
            if(obj.basic_info.agent_logo){
                agent_logo='{{env('IMG_URL')}}'+obj.basic_info.agent_logo;
            }
            html +='          <li class="shadow">\n' +
                '            <a href="/product/show/'+obj.id+'">\n' +
                '            <div class="top">\n' +
                '              <div class="clearfix item_t">\n' +
                '                <div>\n' +
                '                  <img src="'+agent_logo+'" alt="">\n' +
                '                </div>\n' +
                '                <div>\n' +
                '                  <p class="title">'+obj.name+'</p>\n' +
                '                </div>\n' +
                '                <div>\n' +
                '                  <span>'+obj.apply_num+'</span>人申请\n' +
                '                </div>\n' +
                    '                  <p class="clearfix">\n' +tagHtml+
                    '                  </p>\n' +
                '              </div>\n' +
                '              <div class="clearfix loanMsg">\n' +
                '                <div>\n' +
                '                  <p>'+obj.basic_info.rate_start+'%</p>\n' +
                '                  <p>最低月利率</p>\n' +
                '                </div>\n' +
                '                <div>\n' +
                '                  <p>'+obj.basic_info.loan_start+'-'+obj.basic_info.loan_end+'</p>\n' +
                '                  <p>贷款额度(万元)</p>\n' +
                '                </div>\n' +
                '                <div>\n' +
                '                  <p>'+obj.basic_info.repay_start+'-'+obj.basic_info.repay_end+'</p>\n' +
                '                  <p>期限(月)</p>\n' +
                '                </div>\n' +
                '              </div>\n' +
                '            </div>\n' +
                '            <div class="bot clearfix">\n' +
                '              <p>平均下款时间 : '+obj.basic_info.progress_start+'天</p><i class="corner"></i>\n' +
                '            </div>\n' +
                '          </a>\n' +
                '          </li>\n';
        });
        $('#dataList'+curNavIndex).append(html);
    }

    /*联网加载列表数据
     在您的实际项目中,请参考官方写法: http://www.mescroll.com/api.html#tagUpCallback
     请忽略getListDataFromNet的逻辑,这里仅仅是在本地模拟分页数据,本地演示用
     实际项目以您服务器接口返回的数据为准,无需本地处理分页.
     * */
    function getListDataFromNet(curNavIndex,pageNum,pageSize,successCallback,errorCallback) {
        //延时一秒,模拟联网
        setTimeout(function () {
            var url=localStorage.getItem('url_'+curNavIndex);
            if(!url || url===undefined || url==null || url=='null'){
                return false;
            }
            var _token="{{csrf_token()}}";
            $.ajax({
                type: 'post',
                url: url,
                dataType: 'json',
                data:{'_token':_token},
                success: function(data){
                    var listData=data.data.data;
                    //回调
                    successCallback(listData);
                    var nextPageUrl=data.data.next_page_url;
                    if(nextPageUrl){
                        localStorage.setItem('url_'+curNavIndex,nextPageUrl);
                        $('.mescroll-upwarp').removeClass('none');
                    }else {
                        localStorage.setItem('url_'+curNavIndex,null);
                        $('.mescroll-upwarp').addClass('none');
                    }
                },
                error: errorCallback
            });
        },500)
    }
</script>
</body>
</html>